<template>
  <basic-card
    :status="-10"
    :corp-info="corpInfo"
    @confirm="handleUpdate"
    @export="handleExport"
  />
</template>
<script>
import { saveAs } from 'file-saver'
import { getEnvCorpInfo, updateEnvCorpInfo, exportEnvCorpInfo } from '@/api/task/task'
import BasicCard from '../../task/detail-new/BasicCard'
export default {
  name: 'CorpCard',
  components: { BasicCard },
  props: {
    corpId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      corpInfo: {}
    }
  },
  watch: {
    corpId: {
      immediate: true,
      handler: function(val) {
        if (val) this.getCorpInfo()
      }
    }
  },
  methods: {
    async getCorpInfo() {
      const { data } = await getEnvCorpInfo(this.corpId)
      this.corpInfo = data
    },
    omitEmptyItem(arr) {
      const res = []
      arr.forEach(item => {
        const keys = Object.keys(item)
        let flag = false
        keys.forEach(v => {
          if (item[v] || item[v] === 0) flag = true
        })
        flag && res.push(item)
      })
      return res
    },
    async handleUpdate({ formData }) {
      const corpInfo = {
        ...formData,
        busiType: formData.busiType.join(','),
        equipItems: this.omitEmptyItem(formData.equipItems),
        gasEquipmentItems: this.omitEmptyItem(formData.gasEquipmentItems),
        hwItems: this.omitEmptyItem(formData.hwItems),
        reportItems: this.omitEmptyItem(formData.reportItems),
        solidWasteItems: this.omitEmptyItem(formData.solidWasteItems)
      }
      await updateEnvCorpInfo(corpInfo)
      this.$message({
        message: '保存成功',
        type: 'success'
      })
    },
    async handleExport() {
      const { path, filename } = await exportEnvCorpInfo(this.corpId)
      saveAs(path, filename)
    }
  }
}
</script>
